package output;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import calendar.Calendar;
import calendar.Event;
import calendar.Timestamp;

/**
 * See also @Parser
 * @author Monika
 *
 */
public class POSLFileParser extends Parser {

	private static final String CALENDAR_ENTITY_LABEL = "calendar";
	
	//everything after this line will just be rewritten without change
	private static final String BOUNDARY_LINE_REGEX = "\\s*\\%\\s*MAP\\s*";	
	
	public String getFilenamePattern() {
		return "p[0-9]+.posl";
	}
	
	public String getUserCalUrlFromFile(String filename) {
		String url = null;
		try {
			BufferedReader in = new BufferedReader(new FileReader(filename));			
			String line = in.readLine();
			while(line!=null&&url==null){
				line = line.trim();			
				if (line.startsWith(CALENDAR_ENTITY_LABEL+"(")){
					url = line.substring(line.indexOf("http://"));
					url = url.substring(0,url.indexOf(")")-1);					
				}
				line = in.readLine();				
			}
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException ioe){
			ioe.printStackTrace();
		}			
		return url;
	}


	public void writeCalendarData(String filename, Calendar calendar,
			String outfilename) {
		boolean rewriteTheRest=false;
		try{		
			this.out = new BufferedWriter(new FileWriter(outfilename));			
			BufferedReader in = new BufferedReader(new FileReader(filename));			
			String line = in.readLine();
			
			boolean calendarStarted = false;
			boolean calendarEnded = false;
			boolean ignoreCurrentEntity = false;

			while(line!=null){
				String checkLine = line.trim();
				if (rewriteTheRest){
					writeLine(line);
				}else if (checkLine.startsWith("%")){//comment
					if (line.matches(BOUNDARY_LINE_REGEX)){
						rewriteTheRest=true;						
					}
					writeLine(line);					
										//	something(....).					something(....,
				}else if(checkLine.matches(".+\\(.+\\)\\.")||checkLine.matches(".+\\(.+\\,[\\s^\\n]*")){
					//new entity started
					ignoreCurrentEntity=false;						
					String entityName=checkLine.substring(0,checkLine.indexOf("("));						
					int inxOfEnd = checkLine.indexOf(").");
					String args = checkLine.substring(checkLine.indexOf("(")+1,inxOfEnd>0?inxOfEnd:checkLine.length()-1);
					List<String> arrgs = Arrays.asList(args.split(","));

					if ("calendar".equals(entityName)){
						calendarStarted=true;												
						if (line.indexOf(").")>0){													
							calendarEnded=true;
						}

						if (arrgs.size()>=2){
							//set calendarID
							String calendarID = arrgs.get(1);//checkLine.substring(checkLine.indexOf(",")+1);
							//calendarID = calendarID.substring(0,calendarID.indexOf(","));
							calendar.setCalendarID(calendarID);
						}
						writeLine(line);
					}else{
						if ("event".equals(entityName)){
							if (arrgs.contains("Possible")){
								ignoreCurrentEntity=true;
							}else{
								writeLine(line);	
							}
						}else{								
							writeLine(line);								
						}
						if (calendarStarted&&calendarEnded){
							writeNewEvents(calendar);
							calendarStarted=false;
						}
					}
					//						........).											
				}else if(checkLine.matches(".+\\)[\\.]")){
					//the entity ended
					if (calendarStarted&&!calendarEnded){
						calendarEnded=true;
						
						//set calendarID
						String calendarID = checkLine.substring(checkLine.lastIndexOf(",")+1,checkLine.indexOf(")."));
						calendar.setCalendarID(calendarID);

					}
					
					if (!ignoreCurrentEntity){
						writeLine(line);
					}
				//						........,											
				}else if (checkLine.matches(".+,")){
					//we are somewhere in the middle of the entity
					if (!ignoreCurrentEntity){					
						writeLine(line);
					}
				}else{									
					writeLine(line);
				}		
									
				line = in.readLine();
				//'in.readLine()' sometimes does not read empty lines, just skips them..
				//so in output files empty lines are sometimes missing
				//I dont know what it depends on, and how to solve this..				
				//check that: System.out.println("read new line: '"+line+"'");
			}								
			in.close();
			out.close();
			
		}catch(IOException ioe){
			ioe.printStackTrace();
		}
	}

	public void writeNewEvents(Calendar calendar) {
		writeLine("");

		/*	target format:
		 * event(c0002,?:Activity,Possible,
			dateTime[2009:integer,6:integer,15:integer,11:integer,15:integer],
			dateTime[2009:integer,6:integer,15:integer,11:integer,45:integer]).
		 */
		
		for (Event e: calendar.getEvents()){	
			Timestamp t1 = e.getStartTime();
			Timestamp t2 = e.getEndTime();
			
			if (calendar.getCalendarID()==null) System.err.println("OOps calendar ID was not read - it is null!");
			
			writeLine("\tevent("+calendar.getCalendarID()+",?:"+e.getEventTitle()+",Possible,");			
			writeLine("\tdateTime["+t1.getYear()+":integer,"+t1.getMonth()+":integer,"+t1.getDay()+":integer,"+t1.getHour()+":integer,"+t1.getMinute()+":integer],");
			writeLine("\tdateTime["+t2.getYear()+":integer,"+t2.getMonth()+":integer,"+t2.getDay()+":integer,"+t2.getHour()+":integer,"+t2.getMinute()+":integer]).");
			writeLine("");
		}
		
	}	


	
}
